#include "tcpclient.h"

void perr_exit(const char *s)
{
	perror(s);
	exit(1);
}

int Socket(int domain,int type,int protocol)
{
	int fd=socket(domain,type,protocol);
	if(fd==-1)
		perr_exit("socket error!\n");
	return fd;
}

int Bind(int sockfd,const struct sockaddr *addr,socklen_t addrlen)
{
	int ret = bind(sockfd, addr, addrlen);
	if (ret == -1)	
		perr_exit("bind error!\n");
	return ret;
}

int Listen(int sockfd,int backlog)
{
	int ret=listen(sockfd,backlog);
	if(ret==-1)	
		perr_exit("listen error!\n");
	return ret;
}

int Accept(int sockfd,struct sockaddr *addr,socklen_t *addrlen)//慢速系统调用
{
	int ret;
again:
	if( (ret=accept(sockfd,addr,addrlen)) ==-1)
	{
		if(errno==ECONNABORTED || errno==EINTR)
			goto again;
		else
			perr_exit("accept error!\n");
	}
	return ret;
}

int start_up(const char* ip, int port)
{
	int fd = Socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in ser_addr;
	ser_addr.sin_family = AF_INET;
	ser_addr.sin_port = htons(port);
	ser_addr.sin_addr.s_addr = inet_addr(ip);
	int on = 1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int));
	socklen_t addrlen=sizeof(struct sockaddr);
	Bind(fd,(struct sockaddr*)&ser_addr,addrlen);
	Listen(fd,backlogs);
	return fd;
}

//connect() 不会阻塞
int Connect(int sockfd,const struct sockaddr *addr,socklen_t addrlen)
{
	int ret;
	ret = connect(sockfd,addr,addrlen);
	if(ret == -1)
		perr_exit("connect error!\n");
	return ret;
}
 
ssize_t Read(int fd,void *buf,size_t nbytes)
{
	ssize_t n;
again:
	if( (n=read(fd,buf,nbytes))==-1)
	{
		if(errno==EINTR)
			goto again;
		else
			perr_exit("read errror!\n");
	}
	return n;
}
 
ssize_t Write(int fd,void *buf,size_t nbytes)
{
	ssize_t n;
again:
	if( (n=write(fd,buf,nbytes))==-1)
	{
		if(errno==EINTR)
			goto again;
		else
			perr_exit("write errror!\n");
	}
	return n;
}
